<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head lang="en" th:replace="include/common/common :: commonHeader">
    <footer th:include="include/common/common :: layUiResource"></footer>
    <footer th:include="include/common/common :: blueCSSResource"></footer>
    <footer th:include="include/common/common :: zTreeCSSSource"></footer>
    <footer th:include="include/common/common :: zTreeJSSource"></footer>
    <script>
        layui.config({
            base: '/staticResource/layuiadmin/' //静态资源所在路径
        }).extend({
            index: 'lib/index' //主入口模块
        }).use(['index','form','laydate', 'table'] , function () {
            var admin = layui.admin
                ,element = layui.element
                ,laydate = layui.laydate
                ,table = layui.table
                ,form = layui.form;

            element.render();
            /*            laydate.render({
                            elem: '#checkDate'
                        });*/

            let entityName = 'stkInBack'
                // ,pageSize = [[${pageSize}]]
                ,tableId = entityName + "-table-operate"
                ,_billNum = $("#billNum").val()
                ,_billType = $("#billType").val()
                ,isSafe = false
                ,cols = [
                    [
                        {field:'id', title: 'ID', sort: true, hide:true, fixed: 'left'}
                        ,{field:'billNum', title: 'billNum', sort: true, hide:true, fixed: 'left'}
                        ,{title:'操作' , align:'center', fixed: 'right', toolbar: '#' + entityName + '-table-operate-bar'}
                        ,{field:'barcode', sort:true , title: '条码' , edit:true}
                        ,{field:'code', sort:true , title: '商品代码' , edit:true}
                        ,{field:'name', sort:true , title: '商品名称' }
                        ,{field:'spec', sort:true , title: '单位'}
                        ,{field:'unit', sort:true , title: '包装单位'}
                        ,{field:'qpcStr', sort:true , title: '包装规格' , edit:true}
                        ,{field:'qpc', sort:true , title: '包装数量'}
                        ,{field:'oprice', title: '单价'}
                        ,{field:'qtyStr', title: '进货件数', edit:true}
                        ,{field:'qty', sort:true , title: '进货数量' , edit:true}
                        ,{field:'total', title: '金额'}
                    ]
                ];

            $(document).on('click','.zTreeBtn' , function () {
                if (!isSafe){
                    $("#zTreeOption").val($(this).attr('data'));
                    let elementId = $(this).attr('id') , data = JSON.parse($(this).attr('data')) , i = '/a/layTips/treeSelectForm?isUpdateTree=false' , t = data.title;
                    $.fn.blueJs.tools.active['layerOpen'].call(this , i , t);
                }
            });

            let templateData = $.fn.blueJs.tools.active['mapCloneKey'].call(this , cols[0]);

            $(document).ready(function () {
                $.fn.blueJs.tools.formButtonItem(entityName);
                let searchBtn = '#' + entityName + 'SearchBtn' ;
                isSafe = $("#status").val() == "3"?true:false;
                $("#searchBillNum").val(_billNum);
                $("#searchBillType").val(_billType);
                let tableData = $.fn.blueJs.tools.active['getPageData'].call(this , searchBtn);
                $.fn.blueJs.tools.active['tableWriteProtect'].call(this , table , tableId , tableData , cols , isSafe);

                if (isSafe){
                    $.fn.blueJs.tools.formWriteProtect();
                }else {
                    if ($.fn.blueJs.tools.isEmpty(table.cache[tableId])){
                        $.fn.blueJs.tools.active['tableAddRow'].call(this , table , tableId , templateData , 1 , true , 'barcode');
                    }
                }
            });

            function tableRowSumTotal(table , tableId , rowIndex , fieldName , rowQty){
                let _oprice = parseFloat(table.cache[tableId][rowIndex]['oprice']);
                let _total = rowQty*_oprice;
                $.fn.blueJs.tools.active['tableColUpdate'].call(this , table , tableId , rowIndex , fieldName , _total);
            };

            function tableColMove(table , tableId , rowIndex , tableDataLength , templateData) {
                if (rowIndex == tableDataLength - 1){
                    $.fn.blueJs.tools.active['tableAddRow'].call(this , table , tableId , templateData , 1 , true , 'barcode');
                }else {
                    $.fn.blueJs.tools.active['tableReload'].call(this , table , tableId);
                    $.fn.blueJs.tools.active['tableColClick'].call(this , tableId , rowIndex + 1 , 'barcode');
                }
            };

            function updateHeadSumTotal(tableDataList){
                let sumQty = 0 , sumTotal = 0 ;
                $.each(tableDataList , function (i , v) {
                    if ($.fn.blueJs.tools.isNotEmpty(v.code) && v.qty != 0){
                        sumQty = sumQty + parseFloat(v.qty);
                        sumTotal = sumTotal + parseFloat(v.total);
                    }
                });
                $("#qty").val(sumQty);
                $("#total").val(sumTotal);
            };

            function tableUpdateRowByGoods(jsonData , table , tableId , rowIndex){
                let result = $.fn.blueJs.tools.ajaxSubmit('POST' , '/a/stkInBack/getGoods' , jsonData , false , 'JSON');
                if (result.status != 0){
                    layer.msg(result.data);
                }else {
                    let rowData = {
                        barcode:result.data.barcode
                        ,code : result.data.code
                        ,name:result.data.name
                        ,spec:result.data.spec
                        ,unit:result.data.unit
                        ,qpcStr:result.data.qpcStr
                        ,qpc:result.data.qpc
                        ,oprice:result.data.oprice
                    };
                    $.fn.blueJs.tools.active['tableRowUpdate'].call(this , table , tableId , rowIndex , rowData);
                    $.fn.blueJs.tools.active['tableReload'].call(this , table , tableId);
                    $.fn.blueJs.tools.active['tableColClick'].call(this , tableId , rowIndex , 'qtyStr');
                }
            };

            $(document).on('keyup' , '.layui-input' , function (event) {
                switch (event.keyCode) {
                    // 键盘回车事件
                    case 13:
                        let td = $(this).parent('td') , tr = td.parent('tr') , dataIndex = parseInt($(tr).attr("data-index")) , data_field = $(td).attr("data-field")
                            , tableDataList = table.cache[tableId];

                        let _qpc = parseFloat(table.cache[tableId][dataIndex]['qpc']) ,  _qty = parseFloat(table.cache[tableId][dataIndex]['qty'])
                            ,_qpcStr = table.cache[tableId][dataIndex]['qtyStr'] , jsonData = {};
                        switch (data_field) {
                            case 'qtyStr':
                                if ($.fn.blueJs.tools.isEmpty(_qpcStr)){
                                    $.fn.blueJs.tools.active['tableColClick'].call(this , tableId , dataIndex  , 'qty');
                                }else {
                                    let temp = _qpcStr.split("+");
                                    _qty = temp.length > 1?_qpc*parseFloat(temp[0]) + parseFloat(temp[1]):_qpc*parseFloat(_qpcStr);

                                    $.fn.blueJs.tools.active['tableColUpdate'].call(this , table , tableId , dataIndex , 'qty' , _qty);
                                    tableRowSumTotal(table , tableId , dataIndex , 'total' , _qty);
                                    updateHeadSumTotal(tableDataList);
                                    tableColMove(table , tableId , dataIndex , tableDataList.length , templateData);
                                }
                                break;
                            case 'qty':
                                if (_qty % _qpc== 0){
                                    _qpcStr =  _qty/_qpc;
                                }else {
                                    let temp = Math.floor(_qty/_qpc);
                                    _qpcStr = temp == 0?temp + "+" + _qty:temp + "+" + (_qty - _qpc);
                                }

                                $.fn.blueJs.tools.active['tableColUpdate'].call(this , table , tableId , dataIndex , 'qtyStr' , _qpcStr);
                                tableRowSumTotal(table , tableId , dataIndex , 'total' , _qty);
                                updateHeadSumTotal(tableDataList);
                                tableColMove(table , tableId , dataIndex , tableDataList.length , templateData);
                                break;
                            case 'barcode':
                                jsonData = {
                                    barcode: table.cache[tableId][dataIndex]['barcode']
                                };
                                tableUpdateRowByGoods(jsonData , table , tableId , dataIndex);
                                break;
                            case 'code':
                                jsonData = {
                                    code: table.cache[tableId][dataIndex]['code']
                                };
                                tableUpdateRowByGoods(jsonData , table , tableId , dataIndex);
                                break;
                            default:
                                td['nextAll']('[data-edit="true"]:first').click();
                        }
                        break;
                }
            });

            var active = {};

            let tableTrObj = {};
            table.on('tool(' + entityName + '-table-operate)',function(obj){
                if (obj.event = 'detail'){
                    tableTrObj = obj;
                    let i = "/a/" + entityName + "/goodsForm", t = "商品明细";
                    $.fn.blueJs.tools.active['layerOpen'].call(this , i , t);
                }
            });

            window.goodsSelect = function (res) {
                tableTrObj.update({
                    name:res.name
                    ,code:res.code
                    ,barcode:res.barcode
                    ,spec:res.spec
                    ,unit:res.unit
                    ,qpcStr:res.qpcStr
                    ,qpc:res.qpc
                    ,oprice:res.oprice
                });
                $.fn.blueJs.tools.active['tableColClick'].call(this , tableId , tableTrObj.tr.index() , 'qtyStr');
            };

            $('.' + entityName + '-table-operate-btn .layui-btn').on('click', function(){
                let type = $(this).data('type');
                active[type] ? active[type].call(this) : '';
            });

            form.on('submit(' + entityName + 'Save)',function () {
                let formId = $(this).attr("blue-form-id")
                    ,sumTotal = $("#total").val() , sumQty = $("#qty").val();
                if ($.fn.blueJs.tools.isEmpty(sumQty) || sumQty == 0){
                    layer.msg("空表单不允许提交保存！");
                }else {
                    let tableDataList = table.cache[tableId] , submitDataList = {};
                    let objectName = 'stkInBackDtlList';
                    let supplierCode = $("#supplierCode").val(),warCode = $("#warCode").val();

                    $.each(tableDataList , function (i , v) {
                        let code = v.code , qty = v.qty;
                        if ($.fn.blueJs.tools.isNotEmpty(code) && qty != 0){
                            submitDataList[objectName + "["+i+"].id"] = v.id;
                            submitDataList[objectName + "["+i+"].billNum"] = _billNum;
                            submitDataList[objectName + "["+i+"].code"] = code;
                            submitDataList[objectName + "["+i+"].barcode"] = v.barcode;
                            submitDataList[objectName + "["+i+"].name"] = v.name;
                            submitDataList[objectName + "["+i+"].qty"] = v.qty;
                            submitDataList[objectName + "["+i+"].oprice"] = v.oprice;
                            submitDataList[objectName + "["+i+"].total"] = v.total;
                        }
                    });

                    let _id = $("#" + entityName + "Id").val() , _isNewRecord = $("#isNewRecord").val();
                    let jsonData = "?id=" + _id + "&isNewRecord=" + _isNewRecord + "&billType=" + _billType + "&billNum=" + _billNum + "&warCode=" + warCode + "&supplierCode=" + supplierCode + "&qty=" + sumQty + "&total=" + sumTotal
                        ,formUrl = $("#" + formId).attr("action") , msg = "";
                    $.ajax({
                        type:'POST',
                        url:formUrl + jsonData,
                        data:submitDataList,
                        async:false,
                        dataType:'JSON',
                        success:function (data) {
                            let status = data.status;
                            if (status != 0){
                                layer.msg(data.msg + "请联系系统管理员！");
                            }else {
                                let type = 'saveMsg';
                                //当你在iframe页面关闭自身时
                                let index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
                                $.fn.blueJs.tools.active[type].call(this , "单据已保存" , index);
                            }
                        },
                        error:function () {

                        }
                    });


                }
                return false;
            });

            //点击事件监听
            $(document).on('click' , function (event) {
                let targetId = event.target.id;
                let cancelBtn = entityName + "CancelBtn";
                if (targetId == cancelBtn){
                    let index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
                    parent.layer.close(index); //再执行关闭
                }
            });

        });


    </script>
</head>
<body>
<!--  zTree遮罩层 -->
<input type="hidden" id="zTreeOption" value=""/>
<div class="layui-fluid">
    <div class="layui-row layui-col-space15">
        <div class="layui-col-md12">
            <div class="layui-card">
                <div class="layui-card-body">
                    <form class="layui-form" id="stkInBackForm" th:object="${stkInBack}" method="post" action="/a/stkInBack/save">
                        <!--<div class="box-body">-->
                        <div class="blue-form-unit">基本信息</div>
                        <input type="hidden" id="stkInBackId" th:field="*{id}"/>
                        <input type="hidden" id='isNewRecord' th:field="*{isNewRecord}"/>
                        <input type="hidden" id='billType' th:field="*{billType}"/>
                        <input type="hidden" id="status" th:field="*{status}"/>

                        <div class="layui-form-item">
                            <div class="layui-col-md6">
                                <label class="layui-form-label " title=""><span class="blue-required ">*</span>单据号：</label>
                                <div class="layui-input-block">
                                    <input type="text" class="layui-input" id="billNum" readonly th:field="*{billNum}">
                                </div>
                            </div>
                        </div>



                        <div class="layui-form-item">
                            <div class="layui-col-md3">
                                <label class="layui-form-label " title=""><span class="blue-required ">*</span>供应商：</label>
                                <thl:tml type="treeSelect" isShowCode="1" title = "供应商明细" submitAttributeName="code"
                                         url = "/a/supplier/treeData" name = "supplierCode" id = "supplier" submitValue = "*{supplier.code}" showValue = "*{supplier.name}"
                                         canSelectRoot = "false" canSelectParent = "false"/>
                            </div>

                            <div class="layui-col-md3">
                                <label class="layui-form-label " title=""><span class="blue-required ">*</span>仓库：</label>
                                <thl:tml type="treeSelect" isShowCode="1" title = "仓库" submitAttributeName="code"
                                         url = "/a/wareHouse/treeData" name = "warCode" id = "war" submitValue = "*{wareHouse.code}" showValue = "*{wareHouse.name}"
                                         canSelectRoot = "false" canSelectParent = "false"/>
                            </div>

                            <div class="layui-col-md3">
                                <label class="layui-form-label " title=""><span class="blue-required ">*</span>合计数量：</label>
                                <div class="layui-input-block">
                                    <input type="text" class="layui-input" id="qty" lay-verify="required" readonly th:field="*{qty}">
                                </div>
                            </div>

                            <div class="layui-col-md3">
                                <label class="layui-form-label " title=""><span class="blue-required ">*</span>合计金额：</label>
                                <div class="layui-input-block">
                                    <input type="text" id="total" autocomplete="off" lay-verify="required" class="layui-input" readonly th:field="*{total}">
                                </div>
                            </div>

                        </div>

                        <div class="layui-form-item">
                            <div class="layui-col-md3">
                                <label class="layui-form-label " title=""><span class="blue-required ">*</span>制单人：</label>
                                <div class="layui-input-block">
                                    <input type="text" class="layui-input" id="createBy" readonly th:field="*{createBy}">
                                </div>
                            </div>

                            <div class="layui-col-md3">
                                <label class="layui-form-label " title=""><span class="blue-required ">*</span>制单日期：</label>
                                <div class="layui-input-block">
                                    <input type="text" id="createDate"  class="layui-input" readonly th:field="*{createDate}">
                                </div>
                            </div>

                            <div class="layui-col-md3">
                                <label class="layui-form-label " title=""><span class="blue-required ">*</span>记账人：</label>
                                <div class="layui-input-block">
                                    <input type="text" class="layui-input" id="checkBy" readonly th:field="*{checkBy}">
                                </div>
                            </div>

                            <div class="layui-col-md3">
                                <label class="layui-form-label " title=""><span class="blue-required ">*</span>记账日期：</label>
                                <div class="layui-input-block">
                                    <input type="text" id="checkDate" class="layui-input" readonly th:field="*{checkDate}">
                                </div>
                            </div>
                        </div>

                        <div class="layui-form-item">
                            <div class="layui-col-md6">
                                <label class="layui-form-label " title="">备注：</label>
                                <div class="layui-input-block">
                                    <input type="text" id="remarks" class="layui-input" th:field="*{remarks}">
                                </div>
                            </div>
                        </div>

                    </form>
                </div>
            </div>
            <div class="layui-card">

                <!--                        todo:id = entity + search + form-->
                <form class="layui-form" id="stkInBackSearchForm" th:object="${stkInBack}" method="post" action="/a/stkInBack/findPage4Dtl">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <div class="layui-input-inline">
                                <input type="hidden" name="billNum" id="searchBillNum" placeholder="单据号" autocomplete="off" class="layui-input">
                                <input type="hidden" id='searchBillType' th:field="*{billType}"/>
                            </div>
                        </div>
                    </div>

                    <div class="layui-col-lg4">
                        <!--                        todo:blue-form-id = entity + search + form-->
                        <button type="button" style="display: none" class="layui-btn" id="stkInBackSearchBtn" onsubmit="return false" blue-form-id="stkInBackSearchForm">搜索</button>
                    </div>
                </form>

                <div class="layui-card-body">
                    <!--                    <div class="layui-btn-group ordBill-table-operate-btn" id="tableBtn" style="margin-bottom: 10px;">
                                            <button class="layui-btn layui-btn-sm" data-type="add">新增</button>
                                        </div>-->
                    <table class="layui-hide" id="stkInBack-table-operate" lay-filter="stkInBack-table-operate"></table>

                    <script type="text/html" id="stkInBack-table-operate-bar">
                        <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="detail">选择商品</a>
                    </script>
                </div>
            </div>

            <div class="layui-card">
                <div class="layui-card-body">
                    <div class="layui-form-item layui-layout-admin">
                        <div class="layui-input-block blue-form-button-item">
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
</html>




